﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace LX.Cache.Web.Providers
{
    public class HttpRuntimeCacheProvider : ICacheProvider
    {
        public void Set(string key, object value)
        {
            if (HttpContext.Current == null)return ;
            if (string.IsNullOrWhiteSpace(key)) return;

	        HttpRuntime.Cache.Insert(
                    key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration,
	                System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null
	                );
        }

        public void Set(string key, object value, int expiresSecond)
        {
            if (HttpContext.Current == null) return;
            if (string.IsNullOrWhiteSpace(key)) return;

            HttpRuntime.Cache.Insert(
                    key, value, null, DateTime.Now.AddSeconds(expiresSecond),
                    System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null
                    );
        }

        public object GetData(string key)
        {
            return HttpContext.Current == null ? null : HttpRuntime.Cache.Get(key);
        }

        public void Remove(string key)
        {
            if (HttpContext.Current == null) return;
            if (string.IsNullOrWhiteSpace(key)) return;

            HttpRuntime.Cache.Remove(key);
        }

        public void RemoveAll()
        {
            if (HttpContext.Current == null) return;
            var cacheEnum = HttpRuntime.Cache.GetEnumerator();
            var al = new ArrayList();
            while (cacheEnum.MoveNext())
            {
                al.Add(cacheEnum.Key);
            }
            foreach (string key in al)
            {
                HttpRuntime.Cache.Remove(key);
            }
        }
    }
}
